package mall.controller.client;


import mall.core.web.Controller;
import mall.entity.Product;
import mall.service.ProductService;
import mall.service.CategoryService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/client/product")
public class ClientProductController extends Controller {
    private final ProductService service = new ProductService();
    private final CategoryService categoryService = new CategoryService();

    protected void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String keyword = request.getParameter("keyword");
        String categoryId = request.getParameter("categoryId");

        Product product = new Product();
        product.setName(keyword);
        if (categoryId != null && !categoryId.isEmpty()) {
            product.setCategoryId(Integer.parseInt(categoryId));
        }

        List<Product> productList = service.list(product);

        request.setAttribute("categoryId", categoryId);
        request.setAttribute("productList", productList);
        request.setAttribute("categoryList", categoryService.list());
        forward("/index", request, response);

    }


    protected void detail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Product product = service.getById(Integer.parseInt(id));

        if (product == null) {
            redirect("/index", request, response);
            return;
        }


        request.setAttribute("product", product);
        forward("/client/detail", request, response);
    }
}
